﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Net.Mail;
using Abp.Timing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Mt.Site.Application.Dto;
using Mt.Site.Application.Dto.Add;
using Mt.Site.Application.Messages_.BackEnd.Dto;
using Mt.Site.Core.Base.Utils.FileIO;
using Mt.Site.Core.Messages_;
using Mt.Site.Core.Messages_.Permissions;
using Mt.Site.Core.Navigations;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Application.Messages_.BackEnd
{
    public class MessagesAppService : ApplicationService, IMessagesAppService
    {
        public readonly IRepository<Messages, Guid> _messagesRepository;

        public readonly IMessagesManager _messagesManager;

        private readonly IExportMessageHelper _exportMessagesHelper;

        private readonly IMenuStore _menuStore;
        private readonly IEmailSender _sendEmail;
        public MessagesAppService(
                                IRepository<Messages, Guid> messagesRepository,
                                IMessagesManager messagesManager,
                                IMenuStore menustore,
                                 IEmailSender sendEmail,
                                IExportMessageHelper exportMessagesHelper
                               )
        {
            _messagesRepository = messagesRepository;
            _messagesManager = messagesManager;

            _menuStore = menustore;
            _sendEmail = sendEmail;
            _exportMessagesHelper = exportMessagesHelper;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_ExportOut)]
        public async Task<FileDto> DataExport(MesssageExportList input)
        {
            DateTime? startTime = input.StartTime;
            DateTime? endTime = input.EndTime;
            if (endTime == null || startTime == null)
            {
                startTime = null;
                endTime = null;
            }
            if (startTime > endTime)
            {
                startTime = null;
                endTime = null;
            }
            if (input.list != null && input.list.Count > 0)
            {
                var query = _messagesRepository.GetAll()
                               .Where(t => t.MenuId == input.MenuId)
                               .Where(t => input.list.Contains(t.Id));
                query = query.OrderByDescending(item => item.CreationTime);
                var list = await query.ToListAsync();
                return _exportMessagesHelper.MessagesExportDataList(ObjectMapper.Map<List<MessagesDto>>(list));
            }
            else
            {
                var query = _messagesRepository.GetAll()
                          .Where(t => t.MenuId == input.MenuId)
                          .WhereIf(!string.IsNullOrEmpty(input.MenuFilter), item => item.Subhead.Contains(input.MenuFilter))
               .WhereIf(!string.IsNullOrEmpty(input.TitleFilter), item => item.Title.Contains(input.TitleFilter))
              .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), item => item.Name.Contains(input.Filter) || item.CompanyName.Contains(input.Filter) ||
              item.EMail.Contains(input.Filter) || item.Tel.Contains(input.Filter) ||
              item.Phone.Contains(input.Filter))
                          .WhereIf(input.Enabled==1, item => item.IsActive == true)
                          .WhereIf(input.Enabled==2, item => item.IsActive == false)
                          .WhereIf(input.StartTime != null, t => t.CreationTime > startTime)
                          .WhereIf(input.EndTime != null, t => t.CreationTime < endTime);
                query = query.OrderByDescending(item => item.CreationTime);
                var list = await query.ToListAsync();

                return _exportMessagesHelper.MessagesExportDataList(ObjectMapper.Map<List<MessagesDto>>(list));

            }
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_ExportOut)]
        public async Task<FileDto> DataDownExport(MesssageExportList input)
        {
            DateTime? startTime = input.StartTime;
            DateTime? endTime = input.EndTime;
            if (endTime == null || startTime == null)
            {
                startTime = null;
                endTime = null;
            }
            if (startTime > endTime)
            {
                startTime = null;
                endTime = null;
            }
            if (input.list != null && input.list.Count > 0)
            {
                var query = _messagesRepository.GetAll()
                               .Where(t => t.MenuId == input.MenuId)
                               .Where(t => input.list.Contains(t.Id));
                query = query.OrderByDescending(item => item.CreationTime);
                var list = await query.ToListAsync();
                return _exportMessagesHelper.MessagesDownExportDataList(ObjectMapper.Map<List<MessagesDto>>(list));
            }
            else
            {
                var query = _messagesRepository.GetAll()
                          .Where(t => t.MenuId == input.MenuId)
                           .WhereIf(!string.IsNullOrEmpty(input.MenuFilter), item => item.Subhead.Contains(input.MenuFilter))
               .WhereIf(!string.IsNullOrEmpty(input.TitleFilter), item => item.Title.Contains(input.TitleFilter))
              .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), item => item.Name.Contains(input.Filter) || item.CompanyName.Contains(input.Filter) ||
              item.EMail.Contains(input.Filter) || item.Tel.Contains(input.Filter) ||
              item.Phone.Contains(input.Filter))
                          .WhereIf(input.Enabled == 1, item => item.IsActive == true)
                          .WhereIf(input.Enabled == 2, item => item.IsActive == false)
                          .WhereIf(input.StartTime != null, t => t.CreationTime > startTime)
                          .WhereIf(input.EndTime != null, t => t.CreationTime < endTime);
                query = query.OrderByDescending(item => item.CreationTime);
                var list = await query.ToListAsync();

                return _exportMessagesHelper.MessagesDownExportDataList(ObjectMapper.Map<List<MessagesDto>>(list));

            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Delete)]
        public async Task DeleteMessagesAsync(DeleteMessagesInput input)
        {
            var list = await _messagesRepository.GetAllListAsync(item => input.DeleteList.Contains(item.Id));
            foreach (var item in list)
            {
                await _messagesManager.DeleteAsync(item.Id);
            }
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Query)]
        public async Task<PagedResultDto<MessagesDto>> GetPagedMessagesData(PageMessageInput input)
        {
            DateTime? startTime = input.StartTime;
            DateTime? endTime = input.EndTime;

            if (endTime == null || startTime == null)
            {
                startTime = null;
                endTime = null;
            }
            if (startTime > endTime)
            {
                startTime = null;
                endTime = null;
            }
            var query = _messagesRepository.GetAll()
              .Where(item => item.MenuId == input.MenuId)
              .WhereIf(!string.IsNullOrEmpty(input.MenuFilter), item => item.Subhead.Contains(input.MenuFilter))
               .WhereIf(!string.IsNullOrEmpty(input.TitleFilter), item => item.Title.Contains(input.TitleFilter))
              .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), item => item.Name.Contains(input.Filter) || item.CompanyName.Contains(input.Filter) || 
              item.EMail.Contains(input.Filter) || item.Tel.Contains(input.Filter) || 
              item.Phone.Contains(input.Filter))
              .WhereIf(input.Enabled==1, item => item.IsActive == true)
              .WhereIf(input.Enabled==2, item => item.IsActive == false)
              .WhereIf(input.StartTime != null && input.EndTime != null, item => item.CreationTime >= startTime && item.CreationTime <= endTime);
            if (input.TimePhasing > 0)
            {
                if (input.TimePhasing == 1)//1天内
                {
                    var StarTime = DateTime.Now.AddDays(-1);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 7)//1天内
                {
                    var StarTime = DateTime.Now.AddDays(-7);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 15)//1天内
                {
                    var StarTime = DateTime.Now.AddDays(-15);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 30)//1个月
                {
                    var StarTime = DateTime.Now.AddMonths(-1);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 90)//3个月
                {
                    var StarTime = DateTime.Now.AddMonths(-3);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 120)//6个月
                {
                    var StarTime = DateTime.Now.AddMonths(-6);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 365)//12个月
                {
                    var StarTime = DateTime.Now.AddMonths(-12);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
                if (input.TimePhasing == 730)//24个月
                {
                    var StarTime = DateTime.Now.AddMonths(-24);
                    query = from r in query where r.CreationTime > StarTime select r;
                }
            }
            query = query.OrderByDescending(item => item.CreationTime);
            var count = await query.CountAsync();
            var list = await query.PageBy(input).ToListAsync();

            return new PagedResultDto<MessagesDto>(count, ObjectMapper.Map<List<MessagesDto>>(list));

        }

        /// <summary>
        /// 获取栏目数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Query)]
        public async Task<List<MessageSelectItem>> GetMessageSelectMenuData(MessageSelectInput input)
        {

            var query = _messagesRepository.GetAll()
              .Where(item => item.MenuId == input.MenuId);
              
            query = query.OrderByDescending(item => item.CreationTime);
            var List = query.Select(t => t.Subhead).Distinct();
            var count = await query.CountAsync();
            var resultList = new List<MessageSelectItem>();
            foreach (var item in List)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var Messages = new MessageSelectItem();
                    Messages.Title = item;
                    Messages.Value = item;
                    resultList.Add(Messages);
                }
            }
            return new List<MessageSelectItem>(resultList);

        }

        /// <summary>
        /// 获取栏目数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Query)]
        public async Task<List<MessageSelectItem>> GetMessageSelectTitleData(MessageSelectInput input)
        {

            var query = _messagesRepository.GetAll()
              .Where(item => item.MenuId == input.MenuId);

            query = query.OrderByDescending(item => item.CreationTime);
            var List = query.Select(t => t.Title).Distinct();
            var count = await query.CountAsync();
            var resultList = new List<MessageSelectItem>();
            foreach (var item in List)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var Messages = new MessageSelectItem();
                    Messages.Title = item;
                    Messages.Value = item;
                    resultList.Add(Messages);
                }
            }
            return new List<MessageSelectItem>(resultList);

        }

        /// <summary>
        /// 修改记录信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Update)]
        public async Task UpdateMessagesAsync(UpdateMessageInput input)
        {
            var entity = await _messagesRepository.GetAsync(input.Id);
           
            entity.IsActive = input.IsActive;
            entity.BackIntro = input.BackIntro;
           
            //try
            //{
            //    //初次审核（审核状态为处理状态下触发邮件发送）
            //    if (input.Audit > 0 && entity.Audit<1)
            //    {
            //        var templateUrl = FileHelper.MapPath("~/mtsc/EmailTemplate/Feedback.html");
            //        var htmlBody = System.IO.File.ReadAllText(templateUrl);
            //        string Content = "贵司提交的资料已经通过审核，恭喜贵司成为我司的供应商。";  //审核通过
            //        if (input.Audit == 2)
            //        {
            //            Content = "贵司提交的资料已经收到，很抱歉，贵司的资质不符合我司供应商的筛选要求。"; //审核不通过
            //        }
            //        htmlBody = htmlBody.Replace("%Content%", Content);
            //        await _sendEmail.SendAsync(entity.EMail, "泰山石膏有限公司", htmlBody);
            //    }
            //  }
            //catch
            //{

            //}

            await _messagesManager.UpdateAsync(entity);
        }


        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Update)]
        public async Task UpdateMessagesState(MessagesStateInput input)
        {
            var list = await _messagesRepository.GetAllListAsync(item => input.Ids.Contains(item.Id));
            foreach (var item in list)
            {
                item.IsActive = input.Enabled;
                await _messagesManager.UpdateAsync(item);
            }
        }

        /// <summary>
        /// 根据id获取全部会员信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        [AbpAuthorize(MessagesPermissions.Pages_Manage_Messages_Query)]
        public async Task<MessagesDto> GetMessagesByIdAsync(MenuAndIdInput<Guid> input)
        {
            var query = await _messagesRepository.GetAsync(input.Id);
            var dto = ObjectMapper.Map<MessagesDto>(query);
            return dto;
        }
    }
}
